package arkham.net.messages;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * A file message is used by the server to send a file to the client.
 * Only text files may be sent. The file is sent as a string.
 * @author ctheng
 *
 */
public class FileMessage extends Message
{
	
	private String filename;
	private String filedata;
	
	public FileMessage()
	{
		this("", "");
	}
	
	public FileMessage(String filename)
	{
		this(filename, "");
	}

	public FileMessage(String filename, String filedata)
	{
		this.filename = filename;
		this.filedata = filedata;
	}

	/**
	 * @return the filename
	 */
	public String getFilename() {
		return filename;
	}

	/**
	 * @param filename the filename to set
	 */
	public void setFilename(String filename) {
		this.filename = filename;
	}

	/**
	 * @return the filedata
	 */
	public String getFiledata() {
		return filedata;
	}

	/**
	 * @param filedata the filedata to set
	 */
	public void setResponse(String filedata) {
		this.filedata = filedata;
	}

	@Override
	public byte[] toByteArray() {
		// format: request \0 response \0
		byte[] b = new byte[filename.length() + filedata.length() + 2];
		System.arraycopy(filename.getBytes(), 0, b, 0, filename.length());
		b[filename.length()] = 0;
		System.arraycopy(filedata.getBytes(), 0, b, filename.length() + 1, filedata.length());
		b[b.length - 1] = 0;
		return b;
	}

	@Override
	public void fromByteArray(byte[] b) throws IOException
	{
		ByteArrayInputStream bais = new ByteArrayInputStream(b);
		InputStreamReader isr = new InputStreamReader(bais);
		StringBuffer sb1 = new StringBuffer();
		StringBuffer sb2 = new StringBuffer();
		char q;

		while ((q = (char)isr.read()) != '\0')
		{
			sb1.append(q);
		}
		
		while ((q = (char)isr.read()) != '\0')
		{
			sb2.append(q);
		}
		filename = sb1.toString();
		filedata = sb2.toString();
	}

	@Override
	public int getId() {
		// TODO Auto-generated method stub
		return MessageType.FILE_MESSAGE.id();
	}
	
	@Override
	public String toString()
	{
		return filename + "/" + filedata;
	}
	
}
